/*
 * ImportSources module for Netbeans.
 *
 * Copyright (c) 2007, Rogue
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * For queries or bugs, you may contact me via e-mail: roguexz [at] gmail [dot] com
 */
package rogue.netbeans.module.importsources.ui;

import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JTree;
import javax.swing.tree.TreePath;


/**
 * A tree component whose individual node represents a check-box item.
 *
 * @author Rogue
 */
public class JCheckBoxTree extends JTree {
    private JCheckBoxTree instance = null;
    
    /**
     * Creates a new instance of JCheckBoxTree
     *
     * @param rootNode DOCUMENT ME!
     */
    public JCheckBoxTree(JCheckBoxTreeNode rootNode) {
        super(rootNode);
        super.setCellRenderer(new JCheckBoxTreeCellRenderer());
        instance = this;
        this.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent evt) {
                handleSelection(evt.getX(), evt.getY());
            }
        });
    }
    
    private void handleSelection(int x, int y) {
        int row = getRowForLocation(x, y);
        
        if (row == -1) {
            return;
        }
        
        TreePath path = this.getPathForRow(row);
        Rectangle bounds = getPathBounds(path);
        
        // convert to relative distance:
        x -= bounds.x;
        y -= bounds.y;
        
        Object obj = path.getLastPathComponent();
        
        if (obj instanceof JCheckBoxTreeNode) {
            JCheckBoxTreeNode node = (JCheckBoxTreeNode) obj;
            
            // get this nodes renderer.
            JCheckBoxTreeCellRenderer renderer =
                    (JCheckBoxTreeCellRenderer) cellRenderer.
                    getTreeCellRendererComponent(this, obj, isRowSelected(row),
                        isExpanded(row), node.getChildCount() == 0, row,true);
            
            if (renderer.containsPointWithinCheckBox(x, y)) {
                node.negateSelection();
                repaint();
            }
        }
    }
}
